package com.fly.demo.web;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fly.demo.JsonResult;
import com.fly.demo.aspect.annotation.AuthToken;
import com.fly.demo.entity.Welcome;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@Api(tags = "系统配置项刷新接口")
@RequestMapping("/sysconfig")
public class SysConfigController
{
    @Autowired
    Welcome welcome;
    
    @Autowired
    JdbcTemplate jdbcTemplate;
    
    @AuthToken
    @ApiOperation("刷新欢迎语")
    @PostMapping("/refresh")
    @ApiImplicitParam(name = "message", value = "欢迎语", allowableValues = "骝马新跨白玉鞍，战罢沙场月色寒。城头铁鼓声犹震，匣里金刀血未干。,活捉洪真英，生擒李知恩! ", required = true)
    public JsonResult<?> refresh(@RequestHeader String token, String message)
    {
        if (StringUtils.isBlank(message))
        {
            return JsonResult.error("message不能为空");
        }
        boolean success = updateWelcomeMsg(message) > 0;
        return success ? JsonResult.success(message) : JsonResult.error("刷新欢迎语失败");
    }
    
    /**
     * 刷新欢迎语到数据库
     * 
     * @param message
     * @return
     */
    private int updateWelcomeMsg(String message)
    {
        int count = jdbcTemplate.update("UPDATE sys_config SET `value`=?, modify_time=now() WHERE `key` = 'welcome.message'", message);
        if (count > 0)
        {
            log.info("#### autoRefresh to: {}", message);
            // 集群部署无法刷新数据到全部节点
            welcome.setMessage(message);
        }
        return count;
    }
}
